<template>
  <!-- 电子就诊卡页面 -->
  <div class="page-container">
    <el-card class="main-card">
      <template #header>
        <div class="header-section">
          <span class="main-title">电子就诊卡管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="showAddDialog = true" class="action-btn">
              <el-icon><Plus /></el-icon>
              新增就诊卡
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入姓名" 
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-input 
              v-model="searchForm.idCard" 
              placeholder="请输入身份证号" 
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Document /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.cardType" placeholder="卡类型" clearable>
              <el-option label="普通卡" value="普通卡" />
              <el-option label="医保卡" value="医保卡" />
              <el-option label="VIP卡" value="VIP卡" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="状态" clearable>
              <el-option label="正常" value="正常" />
              <el-option label="挂失" value="挂失" />
              <el-option label="注销" value="注销" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset" class="reset-btn">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 电子卡列表表格 -->
      <el-table 
        :data="filteredEcards" 
        style="width: 100%; margin-top: 20px;" 
        stripe 
        highlight-current-row
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="gender" label="性别" width="80" align="center" />
        <el-table-column prop="idCard" label="身份证号" width="180" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="cardNo" label="卡号" width="160" />
        <el-table-column prop="cardType" label="卡类型" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)" 
              :effect="scope.row.status === '正常' ? 'light' : 'plain'"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)" class="action-btn">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button size="small" type="primary" @click="editCard(scope.row)" class="action-btn">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="handleStatusChange(scope.row)" 
              class="action-btn"
              v-if="scope.row.status === '正常'"
            >
              <el-icon><Lock /></el-icon>
              挂失
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteCard(scope.row)" 
              class="action-btn"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑就诊卡弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="showAddDialog" 
      width="600px" 
      class="main-dialog"
      @close="resetForm"
    >
      <el-form :model="cardForm" :rules="rules" ref="cardFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="cardForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="cardForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="cardForm.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="cardForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卡类型" prop="cardType">
              <el-select v-model="cardForm.cardType" placeholder="请选择卡类型" style="width: 100%">
                <el-option label="普通卡" value="普通卡" />
                <el-option label="医保卡" value="医保卡" />
                <el-option label="VIP卡" value="VIP卡" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="cardForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="正常" value="正常" />
                <el-option label="挂失" value="挂失" />
                <el-option label="注销" value="注销" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="cardForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCard" :loading="saveLoading">保存</el-button>
      </template>
    </el-dialog>

    <!-- 电子卡详情弹窗 -->
    <el-dialog title="电子卡详情" v-model="showDetail" width="500px" class="main-dialog">
      <el-descriptions :column="2" border v-if="detail">
        <el-descriptions-item label="姓名">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ detail.gender }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ detail.idCard }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detail.phone }}</el-descriptions-item>
        <el-descriptions-item label="卡号">{{ detail.cardNo }}</el-descriptions-item>
        <el-descriptions-item label="卡类型">{{ detail.cardType }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detail.status)">{{ detail.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="showDetail = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, User, Document, Search, View, Edit, Lock, Delete } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const showAddDialog = ref(false)
const showDetail = ref(false)
const detail = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const cardFormRef = ref()

// 搜索表单
const searchForm = reactive({
  name: '',
  idCard: '',
  cardType: '',
  status: ''
})

// 卡片表单
const cardForm = reactive({
  id: null,
  name: '',
  gender: '',
  idCard: '',
  phone: '',
  cardNo: '',
  cardType: '',
  status: '正常',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  cardType: [
    { required: true, message: '请选择卡类型', trigger: 'change' }
  ]
}

// 电子卡数据（前端模拟）
const ecards = ref([
  { 
    id: 1, 
    name: '张三', 
    gender: '男',
    idCard: '420101200001010001',
    phone: '13800138000',
    cardNo: 'E10001', 
    cardType: '普通卡', 
    status: '正常',
    createTime: '2024-01-15 10:30:00',
    remark: '首次办理'
  },
  { 
    id: 2, 
    name: '李四', 
    gender: '女',
    idCard: '420101199505151234',
    phone: '13900139000',
    cardNo: 'E10002', 
    cardType: '医保卡', 
    status: '正常',
    createTime: '2024-01-16 14:20:00',
    remark: '医保用户'
  },
  { 
    id: 3, 
    name: '王五', 
    gender: '男',
    idCard: '420101198812123456',
    phone: '13700137000',
    cardNo: 'E10003', 
    cardType: '普通卡', 
    status: '挂失',
    createTime: '2024-01-17 09:15:00',
    remark: '卡片丢失'
  },
  { 
    id: 4, 
    name: '赵六', 
    gender: '女',
    idCard: '420101199208088888',
    phone: '13600136000',
    cardNo: 'E10004', 
    cardType: 'VIP卡', 
    status: '正常',
    createTime: '2024-01-18 16:45:00',
    remark: 'VIP客户'
  }
])

// 计算属性
const total = computed(() => filteredEcards.value.length)
const dialogTitle = computed(() => cardForm.id ? '编辑就诊卡' : '新增就诊卡')

// 过滤后的数据
const filteredEcards = computed(() => {
  let result = ecards.value
  
  if (searchForm.name) {
    result = result.filter(item => item.name.includes(searchForm.name))
  }
  if (searchForm.idCard) {
    result = result.filter(item => item.idCard.includes(searchForm.idCard))
  }
  if (searchForm.cardType) {
    result = result.filter(item => item.cardType === searchForm.cardType)
  }
  if (searchForm.status) {
    result = result.filter(item => item.status === searchForm.status)
  }
  
  return result
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '正常': 'success',
    '挂失': 'warning',
    '注销': 'info'
  }
  return statusMap[status] || 'info'
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  ElMessage.success('搜索完成')
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  ElMessage.success('已重置搜索条件')
}

// 查看详情
const viewDetail = (row) => {
  detail.value = row
  showDetail.value = true
}

// 编辑卡片
const editCard = (row) => {
  Object.assign(cardForm, row)
  showAddDialog.value = true
}

// 保存卡片
const saveCard = async () => {
  try {
    await cardFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (cardForm.id) {
      // 编辑
      const index = ecards.value.findIndex(item => item.id === cardForm.id)
      if (index !== -1) {
        ecards.value[index] = { ...cardForm }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增
      const newCard = {
        ...cardForm,
        id: Date.now(),
        cardNo: `E${String(ecards.value.length + 1).padStart(5, '0')}`,
        createTime: new Date().toLocaleString()
      }
      ecards.value.unshift(newCard)
      ElMessage.success('新增成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (cardFormRef.value) {
    cardFormRef.value.resetFields()
  }
  Object.keys(cardForm).forEach(key => {
    cardForm[key] = key === 'status' ? '正常' : ''
  })
  cardForm.id = null
}

// 删除卡片
const deleteCard = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${row.name} 的就诊卡吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const index = ecards.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      ecards.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要将 ${row.name} 的就诊卡状态改为挂失吗？`,
      '确认挂失',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const index = ecards.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      ecards.value[index].status = '挂失'
      ElMessage.success('状态更新成功')
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 页面加载
onMounted(() => {
  console.log('电子就诊卡页面加载完成')
})
</script>

<style scoped>
.page-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.main-card {
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(80,120,200,0.10), 0 1.5px 8px 0 rgba(80,120,200,0.08);
  transition: box-shadow 0.3s;
}

.main-card:hover {
  box-shadow: 0 12px 40px 0 rgba(80,120,200,0.16), 0 2px 12px 0 rgba(80,120,200,0.10);
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #1976d2;
  letter-spacing: 1px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
}

.search-btn, .reset-btn {
  margin-left: 8px;
}

.action-btn {
  margin-right: 8px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  border-radius: 10px;
  overflow: hidden;
}

.el-table__row:hover {
  background: #e3f2fd !important;
}

.main-dialog :deep(.el-dialog__body) {
  border-radius: 12px;
}

.main-dialog :deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

.main-dialog :deep(.el-input__wrapper) {
  border-radius: 8px;
}

.main-dialog :deep(.el-select) {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }
  
  .header-section {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .search-section .el-row {
    margin: 0;
  }
  
  .search-section .el-col {
    margin-bottom: 12px;
  }
}
</style> 